package com.cskaoyan.advice;

import com.cskaoyan.vo.BaseRespVo;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ExceptionControllerAdvice {


    //BindException.class
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ResponseStatus(HttpStatus.OK)
    public BaseRespVo illegalException(MethodArgumentNotValidException ex) {

        BindingResult bindingResult = ex.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String field = fieldError.getField();
        Object rejectedValue = fieldError.getRejectedValue();
        String defaultMessage = fieldError.getDefaultMessage();
        // String message = "你因"+field+"没通过校验，你传入的值为"+rejectedValue+";"+defaultMessage;
        String message = defaultMessage;
        return BaseRespVo.fail(message, 402);
    }

    @ExceptionHandler({InvalidFormatException.class})
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ResponseStatus(HttpStatus.OK)
    public BaseRespVo jsonParseException(InvalidFormatException ex) {
        System.out.println(ex.getMessage());
        Object value = ex.getValue();
        //System.out.println(value);
        return BaseRespVo.fail("你的输入 " + value.toString() + "不合法", 402);
    }



    /*
        授权异常, 用户没有相应权限时会抛出该异常
     */
    @ExceptionHandler(AuthorizationException.class)
    public BaseRespVo authorizationException(AuthorizationException e)  {
        String message = e.getMessage();
        //System.out.println(message);
        return BaseRespVo.fail("你没有该权限", 506);
    }

    /**
     * 登录异常
     * @param e
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public BaseRespVo authenticationException(AuthenticationException e)  {
        String message = e.getMessage();
        //System.out.println(message);
        return BaseRespVo.fail(message, 702);
    }


}
